package com.wang.lotterysystem.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.wang.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.wang.lotterysystem.common.exception.ControllerException;
import com.wang.lotterysystem.common.exception.ServiceException;
import com.wang.lotterysystem.common.pojo.CommonResult;
import com.wang.lotterysystem.controller.enums.UserIdentityEnum;
import com.wang.lotterysystem.controller.param.user.UserMessageLoginParam;
import com.wang.lotterysystem.controller.param.user.UserPasswordLoginParam;
import com.wang.lotterysystem.controller.param.user.UserRegisterParam;
import com.wang.lotterysystem.controller.result.user.UserBaseInfoResult;
import com.wang.lotterysystem.controller.result.user.UserLoginResult;
import com.wang.lotterysystem.controller.result.user.UserRegisterResult;
import com.wang.lotterysystem.service.UserService;
import com.wang.lotterysystem.service.VerificationCodeService;
import com.wang.lotterysystem.service.dto.user.UserDTO;
import com.wang.lotterysystem.service.dto.user.UserLoginDTO;
import com.wang.lotterysystem.service.dto.user.UserRegisterDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Tag(name = "用户相关功能接口")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private VerificationCodeService verificationCodeService;

    @Operation(summary = "用户注册")
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam userRegisterParam) throws JsonProcessingException {
        //打印日志
        log.info("userRegister UserRegisterParam:"+ objectMapper.writeValueAsString(userRegisterParam));
        //调用service层的register方法
        UserRegisterDTO userRegisterDTO = userService.register(userRegisterParam);
        //转换为CommonResult并返回
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO){
        //校验参数
        if (userRegisterDTO == null){
            log.error("用户注册失败");
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        UserRegisterResult result = new UserRegisterResult();
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }

    /**
     * 给指定的手机发送验证码
     * @param phoneNumber 指定的手机号
     * @return 返回是否发送成功
     */
    @Operation(summary = "发送验证码")
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber) throws JsonProcessingException {
        //打印日志
        log.info("为{}用户发送验证码",phoneNumber);
        //调用service层的sendVerificationCode方法
        verificationCodeService.sendVerificationCode(phoneNumber);
        //构造CommonResult并返回
        return CommonResult.success(true);
    }

    @Operation(summary = "密码登录")
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userLogin(@Validated @RequestBody UserPasswordLoginParam loginParam){
        //打印日志
        log.info("password login:{}",loginParam.getLoginName());
        //调用service层的userLogin方法
        UserLoginDTO dto = userService.userLogin(loginParam);
        //转换为CommonResult并返回
        return CommonResult.success(convertToUserLoginResult(dto));
    }

    @Operation(summary = "验证码登录")
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> shortMessageLogin(@Validated @RequestBody UserMessageLoginParam loginParam){
        //打印日志
        log.info("message login:{}",loginParam.getLoginMobile());
        //调用service层的userLogin方法
        UserLoginDTO dto = userService.userLogin(loginParam);
        //转换为CommonResult并返回
        return CommonResult.success(convertToUserLoginResult(dto));
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO dto){
        if (dto == null){
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_BY_PASSWORD_ERROR);
        }
        UserLoginResult result = new UserLoginResult();
        result.setToken(dto.getToken());
        result.setIdentity(dto.getIdentity());
        return result;
    }

    /**
     * 查询用户列表
     * @param identity 用户身份
     * @return 返回指定身份的用户列表 (如果没有指定,则返回所有用户)
     */
    @Operation(summary = "查询用户列表")
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<UserBaseInfoResult>> findUserBaseInfoList(String identity){
        //打印日志
        log.info("findUserList");

        //创建一个用户列表
        List<UserDTO> userDTOS;
        if (!StringUtils.hasText(identity)){
            //如果identity为空
            userDTOS = userService.findUserList(null);
        }else if (UserIdentityEnum.checkForName(identity) != null) {
            //
            userDTOS = userService.findUserList(UserIdentityEnum.checkForName(identity));
        } else {
            throw new ServiceException(ServiceErrorCodeConstants.IDENTITY_ERROR);
        }
        return CommonResult.success(convertToFindUserListResult(userDTOS));
    }

    /**
     * 转换结果
     * @param userDTOS Service层返回的userList
     * @return 返回Controller层返回的userList
     */
    private List<UserBaseInfoResult> convertToFindUserListResult(List<UserDTO> userDTOS) {
        List<UserBaseInfoResult> list = new ArrayList<>();
        for (UserDTO userDTO : userDTOS) {
            UserBaseInfoResult userBaseInfoResult = new UserBaseInfoResult();
            userBaseInfoResult.setIdentity(userDTO.getIdentity());
            userBaseInfoResult.setUserId(userDTO.getUserId());
            userBaseInfoResult.setUserName(userDTO.getUserName());
            list.add(userBaseInfoResult);
        }

        return list;
    }
}
